import { NextResponse, type NextRequest } from 'next/server'; import { getCustomerUser } from '@/app/lib/lumen-auth'; import { commerceDb } from '@/app/lib/commerce-db'; import { isAdmin } from '@/app/lib/admin'; import { describeImageStyle } from '@/app/lib/openai-vision'; // POST /api/admin/orders/[id]/analyze-style // ---------------------------------------------------------------------- // Sends the customer's uploaded custom_style_url to GPT-4o Vision and // returns a textual style description. Persists it on the order row // (custom_style_description + custom_style_analyzed_at) so subsequent // admin sessions can reuse it without re-paying the Vision call. // // Why this exists: OpenAI's /v1/images/edits endpoint only accepts one // reference image. Without this analysis step, custom-style commissions // generated via OpenAI would silently ignore the customer's uploaded // style and just render the pet against the catalog default. With the // description injected into the prompt, OpenAI now mimics the style by // reading it — Gemini still sees the image directly and benefits too. export const runtime = 'nodejs'; export const dynamic = 'force-dynamic'; export async function POST( _req: NextRequest, ctx: { params: Promise<{ id: string }> }, ) { const { id } = await ctx.params; const user = await getCustomerUser(); if (!user || !isAdmin(user.email)) { return NextResponse.json({ error: 'forbidden' }, { status: 403 }); } const admin = commerceDb(); const { data: order, error: orderErr } = await admin .from('orders') .select('id, custom_style_url') .eq('id', id) .single(); if (orderErr || !order) { return NextResponse.json({ error: 'order not found' }, { status: 404 }); } if (!order.custom_style_url) { return NextResponse.json( { error: 'order has no custom_style_url to analyze' }, { status: 400 }, ); } let description: string; try { description = await describeImageStyle(order.custom_style_url); } catch (e) { const msg = e instanceof Error ? e.message : String(e); return NextResponse.json({ error: `vision failed: ${msg}` }, { status: 500 }); } const analyzedAt = new Date().toISOString(); const { error: updErr } = await admin .from('orders') .update({ custom_style_description: description, custom_style_analyzed_at: analyzedAt, }) .eq('id', id); if (updErr) { return NextResponse.json({ error: `update failed: ${updErr.message}` }, { status: 500 }); } return NextResponse.json({ description, analyzedAt }); }